package com.zhiwen.lockdemo;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/12/19 16:26
 * @Description:
 */
public class LunXunThread02 {
    public static void main(String[] args) {
        LunDemo lunDemo = new LunDemo();
        new Thread(lunDemo.runnable01, "A").start();
        new Thread(lunDemo.runnable02, "B").start();
    }
}

class LunDemo {
    private static int i = 0;
    private static boolean lock = true;
    public Runnable runnable01 = new Runnable() {
        public void run() {
            while (i < 10) {
                synchronized (this) {
                    if (!lock) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                        }
                        System.out.println(Thread.currentThread().getName() + ":" + i++);
                        lock = true;
                    }
                }

            }
        }
    };
    public Runnable runnable02 = new Runnable() {
        public void run() {
            while (i < 10) {
                synchronized (this) {
                    if (lock) {

                        System.out.println(Thread.currentThread().getName() + ":" + i++);
                        lock = false;
                    }
                }

            }
        }
    };

}